package br.com.speedprevweb.dao.impl;

import br.com.speedprevweb.dao.AverbacaoMatriculaDao;
import br.com.speedprevweb.model.AverbacaoMatricula;
import br.com.speedprevweb.util.HibernateUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class AverbacaoMatriculaDaoImpl implements AverbacaoMatriculaDao {

  private boolean valid(AverbacaoMatricula averbacaoMatricula) {
    if (averbacaoMatricula.getNmFantasiaInstituicao().isEmpty()) {
      return false;
    } else {
      return !averbacaoMatricula.getNuCnpjInstituicao().isEmpty();
    }
  }

  @Override
  public boolean inserir(AverbacaoMatricula averbacaoMatricula) {
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
      tx = session.beginTransaction();
      if (valid(averbacaoMatricula)) {
        session.save(averbacaoMatricula);
        return true;
      }
    } catch (HibernateException e) {
      tx.rollback();
      throw e;
    }
    return false;
  }

  @Override
  public boolean alterar(AverbacaoMatricula averbacaoMatricula) {
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
      tx = session.beginTransaction();
      if (valid(averbacaoMatricula)) {
        session.update(averbacaoMatricula);
        return true;
      }
    } catch (HibernateException e) {
      tx.rollback();
      throw e;
    }
    return false;
  }

  @Override
  public boolean excluir(AverbacaoMatricula averbacaoMatricula) {
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
      tx = session.beginTransaction();
      session.delete(averbacaoMatricula);
      return true;
    } catch (HibernateException e) {
      tx.rollback();
      throw e;
    }
  }

  @Override
  public AverbacaoMatricula getAverbacaoMatricula(AverbacaoMatricula averbacaoMatricula) {
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    String sql = "FROM AverbacaoMatricula am where am.idAverbacaoMatricula = :pId";
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery(sql);
      query.setInteger("pId", averbacaoMatricula.getIdAverbacaoMatricula());
      return (AverbacaoMatricula) query.uniqueResult();
    } catch (HibernateException e) {
      tx.rollback();
      throw e;
    }
  }

  @Override
  public List listarTodos() {
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    String sql = "FROM AverbacaoMatricula am order by am.dsAverbacaoMatricula";
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery(sql);
      return query.list();
    } catch (HibernateException e) {
      tx.rollback();
      throw e;
    }
  }    
}
